package org.hako.recite.word.parser.impl;

import java.io.IOException;
import java.io.InputStream;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.hako.recite.word.model.Word;
import org.hako.recite.word.parser.WordList;
import org.hako.recite.word.parser.WordListParseException;

/**
 * Word list parser for excel.
 * 
 * @since 0.4.0
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class ExcelWordListParser extends AbstractWordListParser {

	@Override
	public WordList parse(InputStream inputStream)
			throws WordListParseException {
		try {
			return doParse(inputStream);
		} catch (Exception e) {
			throw new WordListParseException(e);
		}
	}

	/**
	 * Do parse action.
	 * 
	 * @param inputStream
	 * @return word list
	 * @throws IOException
	 * @throws BiffException
	 * @throws IndexOutOfBoundsException
	 */
	private WordList doParse(InputStream inputStream) throws IOException,
			BiffException, IndexOutOfBoundsException {
		Workbook workbook = Workbook.getWorkbook(inputStream);
		Sheet sheet = workbook.getSheet(0);
		int columns = sheet.getColumns();
		int rows = sheet.getRows();
		WordList wordList = new WordList();
		for (int row = 0; row < rows; row++) {
			String[] cells = new String[columns];
			for (int column = 0; column < columns; column++) {
				Cell cell = sheet.getCell(column, row);
				cells[column] = cell.getContents();
			}
			if (row == 0) {
				wordList.setColumnTitles(cells);
			} else {
				wordList.addWord(new Word(cells));
			}
		}
		return wordList;
	}

}
